package usersBody

import (
	"gin/common/lib/gorm"
	"gin/dao/entity"
	"gin/model/body"
)

// Add 添加身体参数
func Add(body entity.UsersBody) {
	gorm.GinDb.SubTable("cmf_users_body", body.Uid).Create(&body)
}

// GetInfo 获取身体参数
func GetInfo(uid int64, recordData string) entity.UsersBody {
	info := entity.UsersBody{}
	gorm.GinDb.SubTable("cmf_users_body", uid).
		Where("uid = ? and record_date = ?", uid, recordData).
		Limit(1).Find(&info)
	return info
}

// Update 修改身体参数
func Update(body entity.UsersBody, id int64) {
	gorm.GinDb.SubTable("cmf_users_body", body.Uid).
		Where("id = ?", id).
		Updates(&body)
}

// GetNew 获取该用户最新的用户参数
func GetNew(uid int64) entity.UsersBody {
	info := entity.UsersBody{}
	gorm.GinDb.SubTable("cmf_users_body", uid).
		Where("uid = ?", uid).
		Order("id desc").Limit(1).Find(&info)
	return info
}

// ChartList 获取用户身体参数列表
func ChartList(p body.UsersBodySelect) (list []*entity.SimpleUsersBody) {
	tx := gorm.GinDb.SubTable("cmf_users_body", p.Uid)
	switch p.Genre {
	case 1:
		if p.DateType == 3 {
			tx.Select("height as record_data,MONTH(create_at) AS record_date")
		} else {
			tx.Select("height as record_data,record_date")
		}
	case 2:
		if p.DateType == 3 {
			tx.Select("weight as record_data,MONTH(create_at) AS record_date")
		} else {
			tx.Select("weight as record_data,record_date")
		}
	case 3:
		if p.DateType == 3 {
			tx.Select("body_fat as record_data,MONTH(create_at) AS record_date")
		} else {
			tx.Select("body_fat as record_data,record_date")
		}
	case 4:
		if p.DateType == 3 {
			tx.Select("bmi as record_data,MONTH(create_at) AS record_date")
		} else {
			tx.Select("bmi as record_data,record_date")
		}
	}
	tx.Where("uid = ? and create_at between ? and ?", p.Uid, p.BeginTime, p.EndTime)
	if p.DateType == 3 {
		tx.Group("Month(create_at)")
	}

	tx.Find(&list)
	return list
}

// List 获取用户身体参数列表
func List(p body.UsersBodyList) (list []*entity.SimpleUsersBody, count int64) {
	tx := gorm.GinDb.SubTable("cmf_users_body", p.Uid)
	switch p.Genre {
	case 1:
		tx.Select("id, height as record_data, record_date")
	case 2:
		tx.Select("id, weight as record_data,record_date")
	case 3:
		tx.Select("id, body_fat as record_data,record_date")
	case 4:
		tx.Select("id, bmi as record_data,record_date")
	}
	tx.Where("uid = ? ", p.Uid).Order("id desc").Offset(p.GetOffset()).Limit(p.GetLength()).Find(&list)
	count = ListCount(p)
	return
}

// ListCount 列表数量
func ListCount(p body.UsersBodyList) (count int64) {
	gorm.GinDb.SubTable("cmf_users_body", p.Uid).Where("uid = ?", p.Uid).Count(&count)
	return
}

// GetDetail 获取详情信息
func GetDetail(p body.UserBodyInfo) (detail entity.DetailUsersBody) {
	gorm.GinDb.SubTable("cmf_users_body", p.Uid).Where("id = ?", p.Id).Limit(1).Find(&detail)
	return
}

// Del 删除
func Del(p body.UserBodyInfo) {
	gorm.GinDb.SubTable("cmf_users_body", p.Uid).Where("id = ?", p.Id).Delete(&entity.UsersBody{})
}
